using System;
using System.IO;
using System.Text;

namespace Kotonoha.Server.Utils {
    class StreamPositionReader {
        private readonly byte endl;

        private readonly Stream stream;
        private readonly Encoding encoding;
        private long returntedPosition = 0;
        private long position;
        private long bufferPosition;
        private readonly byte[] buffer = new byte[4096];
        private int bytesRead;

        public StreamPositionReader(Stream stream, Encoding encoding) {
            this.stream = stream;
            this.encoding = encoding;
            position = 0;
            bufferPosition = 0;
            endl = encoding.GetBytes("\n")[0];
            position += (bytesRead = stream.Read(buffer, 0, buffer.Length));
        }

        private void updateBuffer() {
            Array.Copy(buffer, bufferPosition, buffer, 0, buffer.LongLength - bufferPosition);
            int num = stream.Read(buffer, (int) (buffer.Length - bufferPosition), (int) bufferPosition);
            bytesRead = (int) (buffer.Length - bufferPosition) + num;
            position += num;
            bufferPosition = 0;
        }

        public string ReadLine() {
            if (bufferPosition > 3500) {
                updateBuffer();
            }
            int end = Array.IndexOf(buffer, endl, (int) bufferPosition);
            if (end == -1) {
                end = bytesRead;
            }
            returntedPosition += end - bufferPosition + 1;
            string s = encoding.GetString(buffer, (int)bufferPosition, (int)(end - bufferPosition));
            bufferPosition  = end + 1;
            return s.Trim();
        }

        public long Position {
            get {
                return returntedPosition;
            }
        }

        public bool EndOfStream {
            get {
                return stream.Length == position;
            }
        }
    }
}